/**
 * 工作流主界面组件
 * 负责管理工作流的设计和编辑功能
 */
class AppMainWorkflow {  constructor() {
    this.isVisible = false;
    this.container = null;
    this.canvas = null;
    this.reactFlowInstance = null;
    this.reactRoot = null; // 添加React根实例存储
    this.nodes = [];
    this.edges = [];
    this.selectedNode = null;
    this.nodeCounter = 0;
    
    // 节点类型配置
    this.nodeTypes = {
      input: { icon: '📥', color: '#4CAF50', label: '输入节点' },
      process: { icon: '⚙️', color: '#2196F3', label: '处理节点' },
      decision: { icon: '❓', color: '#FF9800', label: '判断节点' },
      output: { icon: '📤', color: '#9C27B0', label: '输出节点' },
      llm: { icon: '🤖', color: '#F44336', label: 'LLM节点' },
      rag: { icon: '📚', color: '#795548', label: 'RAG节点' }
    };
  }  /**
   * 初始化工作流组件
   */
  async init() {
    await this.loadWorkflowHTML();
    await this.loadWorkflowCSS();
    this.bindElements();
    this.bindEvents();
    // 延迟初始化ReactFlow，确保DOM已完全加载
    setTimeout(() => {
      if (this.isVisible) {
        this.initReactFlow();
      }
    }, 100);
  }

  /**
   * 加载工作流HTML内容
   */
  async loadWorkflowHTML() {
    try {
      const response = await fetch('./components/app-main-workflow.html');
      const workflowHTML = await response.text();
      
      // 查找现有的工作流容器
      const existingWorkflow = document.querySelector('.app-main-workflow');
      if (existingWorkflow) {
        existingWorkflow.outerHTML = workflowHTML;
      } else {
        // 如果没有现有容器，添加到main-content区域
        const mainContent = document.querySelector('.main-content') || document.body;
        mainContent.insertAdjacentHTML('beforeend', workflowHTML);
      }
    } catch (error) {
      console.error('加载工作流HTML失败:', error);
    }
  }

  /**
   * 加载工作流CSS样式
   */
  async loadWorkflowCSS() {
    try {
      // 检查是否已经加载过CSS
      const existingLink = document.querySelector('link[href*="app-main-workflow.css"]');
      if (existingLink) return;

      const link = document.createElement('link');
      link.rel = 'stylesheet';
      link.href = './components/app-main-workflow.css';
      document.head.appendChild(link);
    } catch (error) {
      console.error('加载工作流CSS失败:', error);
    }
  }

  /**
   * 绑定DOM元素
   */
  bindElements() {
    this.container = document.getElementById('app-main-workflow');
    this.canvas = document.getElementById('workflow-canvas');
    this.saveBtn = document.getElementById('workflow-save-btn');
    this.loadBtn = document.getElementById('workflow-load-btn');
    this.clearBtn = document.getElementById('workflow-clear-btn');
    this.propertiesPanel = document.getElementById('node-properties');
  }

  /**
   * 绑定事件监听器
   */
  bindEvents() {
    // 工具栏按钮事件
    if (this.saveBtn) {
      this.saveBtn.addEventListener('click', () => this.saveWorkflow());
    }
    
    if (this.loadBtn) {
      this.loadBtn.addEventListener('click', () => this.loadWorkflow());
    }
    
    if (this.clearBtn) {
      this.clearBtn.addEventListener('click', () => this.clearWorkflow());
    }

    // 节点拖拽事件
    this.bindNodeDragEvents();
  }
  /**
   * 绑定节点拖拽事件
   */
  bindNodeDragEvents() {
    const nodeTypes = document.querySelectorAll('.node-type');
    console.log('Found node types:', nodeTypes.length);
    
    nodeTypes.forEach(nodeType => {
      nodeType.addEventListener('dragstart', (e) => {
        const type = nodeType.dataset.type;
        console.log('Drag start:', type);
        e.dataTransfer.setData('application/reactflow', type);
        e.dataTransfer.effectAllowed = 'move';
      });
    });

    // 画布拖拽事件
    if (this.canvas) {
      this.canvas.addEventListener('dragover', (e) => {
        e.preventDefault();
        e.dataTransfer.dropEffect = 'move';
      });

      this.canvas.addEventListener('drop', (e) => {
        e.preventDefault();
        const type = e.dataTransfer.getData('application/reactflow');
        console.log('Drop event:', type, 'ReactFlow instance:', !!this.reactFlowInstance);
          if (type) {
          const reactFlowBounds = this.canvas.getBoundingClientRect();
          const position = window.reactHelpers.projectPosition(
            this.reactFlowInstance, 
            e.clientX, 
            e.clientY, 
            reactFlowBounds
          );
          
          console.log('Adding node at position:', position);
          this.addNode(type, position);
        }
      });
    } else {
      console.error('Canvas element not found for drag events');
    }
  }  /**
   * 初始化React Flow
   */
  async initReactFlow() {
    if (!this.canvas) {
      console.error('Canvas element not found');
      return;
    }

    try {
      // 检查React和ReactFlow是否已经可用
      if (!window.reactHelpers || !window.reactHelpers.isReactFlowAvailable()) {
        console.error('React or ReactFlow not available');
        return;
      }
      
      // 如果没有任何节点，创建一个初始节点
      if (this.nodes.length === 0) {
        const initialNodes = [
          {
            id: 'start-node',
            type: 'default',
            position: { x: 250, y: 50 },
            data: { label: '🚀 开始节点', nodeType: 'input' },
            style: { 
              background: '#4CAF5020', 
              border: '2px solid #4CAF50',
              borderRadius: '8px',
              padding: '10px',
              color: '#333',
              fontSize: '12px',
              width: '120px',
              textAlign: 'center'
            }
          }
        ];
        this.nodes = initialNodes;
      }

      console.log('Initializing React Flow with', this.nodes.length, 'nodes:', this.nodes);

      // 准备工作流配置
      const workflowConfig = {
        nodes: this.nodes,
        edges: this.edges,
        nodeTypes: this.nodeTypes,
        callbacks: {
          onNodesChange: (changes) => this.onNodesChange(changes),
          onEdgesChange: (changes) => this.onEdgesChange(changes),
          onConnect: (connection) => this.onConnect(connection),
          onInit: (instance) => {
            this.reactFlowInstance = instance;
            console.log('React Flow initialized successfully with', this.nodes.length, 'nodes');
          },
          onNodeClick: (event, node) => this.onNodeClick(event, node)
        }
      };

      // 使用 reactHelpers 初始化工作流
      this.reactRoot = window.reactHelpers.initWorkflow(this.canvas, workflowConfig);

    } catch (error) {
      console.error('初始化React Flow失败:', error);
    }
  }/**
   * 添加新节点
   */
  addNode(type, position) {
    const nodeConfig = this.nodeTypes[type];
    if (!nodeConfig) {
      console.error('Unknown node type:', type);
      return;
    }

    const newNode = {
      id: `node_${++this.nodeCounter}`,
      type: 'default',
      position,
      data: { 
        label: `${nodeConfig.icon} ${nodeConfig.label}`,
        nodeType: type
      },
      style: { 
        background: nodeConfig.color + '20',
        border: `2px solid ${nodeConfig.color}`,
        borderRadius: '8px',
        padding: '10px',
        color: '#333',
        fontSize: '12px',
        width: '120px',
        textAlign: 'center'
      }
    };

    console.log('Adding new node:', newNode);
    this.nodes = [...this.nodes, newNode];
    
    // 如果ReactFlow还没有初始化，先尝试初始化
    if (!this.reactFlowInstance && this.isVisible) {
      console.log('ReactFlow not initialized, initializing now...');
      // 延迟一点时间确保节点已经添加到数组中
      setTimeout(() => {
        this.initReactFlow();
      }, 50);
    } else if (this.reactFlowInstance) {
      this.updateReactFlow();
    } else {
      console.log('Node added to array, will be rendered when ReactFlow is initialized');
    }
  }  /**
   * 更新React Flow
   */
  updateReactFlow() {
    if (this.reactFlowInstance) {
      console.log('Updating React Flow with nodes:', this.nodes.length, 'edges:', this.edges.length);
      // 使用preload.js中的方法更新ReactFlow
      window.reactHelpers.updateReactFlowInstance(this.reactFlowInstance, this.nodes, this.edges);
    } else {
      console.warn('React Flow instance not available');
    }
  }/**
   * 节点变化处理
   */
  onNodesChange(changes) {
    // 处理节点位置、选中状态等变化
    console.log('Nodes changed:', changes);
    
    // 应用节点变化，但不触发更新以避免无限循环
    this.nodes = this.applyNodeChanges(changes, this.nodes);
    console.log('Updated nodes:', this.nodes);
  }

  /**
   * 边变化处理
   */
  onEdgesChange(changes) {
    // 处理边的变化
    console.log('Edges changed:', changes);
    
    // 应用边变化，但不触发更新以避免无限循环
    this.edges = this.applyEdgeChanges(changes, this.edges);
  }

  /**
   * 应用节点变化
   */
  applyNodeChanges(changes, nodes) {
    return changes.reduce((acc, change) => {
      switch (change.type) {
        case 'position':
          return acc.map(node => 
            node.id === change.id 
              ? { ...node, position: change.position }
              : node
          );
        case 'select':
          return acc.map(node => 
            node.id === change.id 
              ? { ...node, selected: change.selected }
              : node
          );        case 'remove':
          return acc.filter(node => node.id !== change.id);
        case 'reset':
          return acc.map(node => 
            node.id === change.id 
              ? { ...node, selected: false, ...change.item }
              : node
          );
        default:
          return acc;
      }
    }, nodes);
  }

  /**
   * 应用边变化
   */
  applyEdgeChanges(changes, edges) {
    return changes.reduce((acc, change) => {
      switch (change.type) {
        case 'select':
          return acc.map(edge => 
            edge.id === change.id 
              ? { ...edge, selected: change.selected }
              : edge
          );
        case 'remove':
          return acc.filter(edge => edge.id !== change.id);
        default:
          return acc;
      }
    }, edges);
  }

  /**
   * 连接处理
   */
  onConnect(connection) {
    const newEdge = {
      ...connection,
      id: `edge_${Date.now()}`,
      type: 'smoothstep'
    };
    
    this.edges = [...this.edges, newEdge];
    this.updateReactFlow();
  }

  /**
   * 节点点击处理
   */
  onNodeClick(event, node) {
    this.selectedNode = node;
    this.showNodeProperties(node);
  }

  /**
   * 显示节点属性
   */
  showNodeProperties(node) {
    if (!this.propertiesPanel) return;

    const nodeType = node.data.nodeType || 'default';
    const nodeConfig = this.nodeTypes[nodeType] || { label: '未知节点' };

    this.propertiesPanel.innerHTML = `
      <div class="property-group">
        <label class="property-label">节点ID</label>
        <input type="text" class="property-input" value="${node.id}" readonly>
      </div>
      
      <div class="property-group">
        <label class="property-label">节点类型</label>
        <input type="text" class="property-input" value="${nodeConfig.label}" readonly>
      </div>
      
      <div class="property-group">
        <label class="property-label">节点标签</label>
        <input type="text" class="property-input" id="node-label" value="${node.data.label}" 
               onchange="appMainWorkflow.updateNodeLabel('${node.id}', this.value)">
      </div>
      
      <div class="property-group">
        <label class="property-label">位置 X</label>
        <input type="number" class="property-input" value="${Math.round(node.position.x)}" readonly>
      </div>
      
      <div class="property-group">
        <label class="property-label">位置 Y</label>
        <input type="number" class="property-input" value="${Math.round(node.position.y)}" readonly>
      </div>
      
      ${this.getNodeTypeSpecificProperties(nodeType)}
    `;
  }

  /**
   * 获取节点类型特定属性
   */
  getNodeTypeSpecificProperties(nodeType) {
    switch (nodeType) {
      case 'llm':
        return `
          <div class="property-group">
            <label class="property-label">模型名称</label>
            <select class="property-select" id="llm-model">
              <option value="gpt-3.5-turbo">GPT-3.5 Turbo</option>
              <option value="gpt-4">GPT-4</option>
              <option value="claude">Claude</option>
              <option value="llama2">Llama 2</option>
            </select>
          </div>
          <div class="property-group">
            <label class="property-label">提示词</label>
            <textarea class="property-input property-textarea" id="llm-prompt" placeholder="输入提示词..."></textarea>
          </div>`;
      
      case 'rag':
        return `
          <div class="property-group">
            <label class="property-label">知识库</label>
            <select class="property-select" id="rag-database">
              <option value="default">默认知识库</option>
              <option value="technical">技术文档</option>
              <option value="business">业务文档</option>
            </select>
          </div>
          <div class="property-group">
            <label class="property-label">检索数量</label>
            <input type="number" class="property-input" id="rag-top-k" value="5" min="1" max="20">
          </div>`;
      
      case 'decision':
        return `
          <div class="property-group">
            <label class="property-label">判断条件</label>
            <textarea class="property-input property-textarea" id="decision-condition" placeholder="输入判断条件..."></textarea>
          </div>`;
      
      default:
        return '';
    }
  }

  /**
   * 更新节点标签
   */
  updateNodeLabel(nodeId, newLabel) {
    this.nodes = this.nodes.map(node => {
      if (node.id === nodeId) {
        return {
          ...node,
          data: { ...node.data, label: newLabel }
        };
      }
      return node;
    });
    
    this.updateReactFlow();
  }

  /**
   * 保存工作流
   */
  saveWorkflow() {
    const workflow = {
      nodes: this.nodes,
      edges: this.edges,
      timestamp: new Date().toISOString()
    };

    const dataStr = JSON.stringify(workflow, null, 2);
    const dataBlob = new Blob([dataStr], { type: 'application/json' });
    
    const link = document.createElement('a');
    link.href = URL.createObjectURL(dataBlob);
    link.download = `workflow_${Date.now()}.json`;
    link.click();
    
    window.showNotification('工作流已保存', 'success');
  }

  /**
   * 加载工作流
   */
  loadWorkflow() {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = '.json';
    
    input.onchange = (e) => {
      const file = e.target.files[0];
      if (!file) return;
      
      const reader = new FileReader();
      reader.onload = (e) => {
        try {
          const workflow = JSON.parse(e.target.result);
          this.nodes = workflow.nodes || [];
          this.edges = workflow.edges || [];
          this.nodeCounter = Math.max(...this.nodes.map(n => 
            parseInt(n.id.replace('node_', '')) || 0
          )) || 0;
          
          this.updateReactFlow();
          window.showNotification('工作流已加载', 'success');
        } catch (error) {
          console.error('加载工作流失败:', error);
          window.showNotification('加载工作流失败', 'error');
        }
      };
      
      reader.readAsText(file);
    };
    
    input.click();
  }
  /**
   * 清空工作流
   */
  clearWorkflow() {
    if (confirm('确定要清空当前工作流吗？此操作不可撤销。')) {
      this.nodes = [];
      this.edges = [];
      this.nodeCounter = 0;
      this.selectedNode = null;
        // 清理React根实例
      if (this.reactRoot) {
        window.reactHelpers.unmountRoot(this.reactRoot);
        this.reactRoot = null;
      }
      
      this.reactFlowInstance = null;
      
      // 清空canvas内容
      if (this.canvas) {
        this.canvas.innerHTML = '';
      }
      
      if (this.propertiesPanel) {
        this.propertiesPanel.innerHTML = '<p class="no-selection">请选择一个节点查看属性</p>';
      }
      
      window.showNotification('工作流已清空', 'success');
    }
  }/**
   * 显示工作流界面
   */
  show() {
    if (this.container) {
      this.container.style.display = 'block';
      this.isVisible = true;
      
      // 确保DOM已经渲染完成后再初始化React Flow
      setTimeout(() => {
        if (!this.reactFlowInstance) {
          console.log('Initializing React Flow...');
          this.initReactFlow();
        } else {
          // 如果ReactFlow已经存在，确保重新渲染当前的节点和边
          this.updateReactFlow();
        }
          // 重新调整React Flow视图
        setTimeout(() => {
          window.reactHelpers.fitView(this.reactFlowInstance);
        }, 200);
      }, 100);
    }
  }

  /**
   * 隐藏工作流界面
   */
  hide() {
    if (this.container) {
      this.container.style.display = 'none';
      this.isVisible = false;
    }
  }

  /**
   * 获取当前可见状态
   */
  isWorkflowVisible() {
    return this.isVisible;
  }
}

// 创建全局实例供属性面板使用
window.appMainWorkflow = null;

// 导出组件类
window.AppMainWorkflow = AppMainWorkflow;
